<template>
  <div style="position: relative;">
    <el-form
      ref="form"
      :size="layoutStore.defaultFormItemSize"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormFlowClassOrderAI()" @reset="reset">
        <el-form-item label="班级名称">
          <el-input
            class="filter-item"
            v-model="formFilter.classNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="班级级别">
          <el-select
            class="filter-item"
            v-model="formFilter.classLevelFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="classLevelFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in classLevelFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="流程状态" prop="formFilter.flowStatus">
          <el-select class="filter-item" v-model="formFilter.flowStatus" :clearable="true"
            placeholder="流程状态">
            <el-option v-for="item in StaticDict.SysFlowWorkOrderStatus.getList()" :key="item.id"
              :label="item.name" :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期" prop="formFilter.createTime">
          <date-range class="filter-item" v-model="formFilter.createTime" :clearable="true" :allowTypes="['day']" align="left"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="工单编号" prop="formFilter.workOrderCode">
          <el-input class="filter-item" v-model="formFilter.workOrderCode"
            :clearable="true" placeholder="工单编号"
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      class="page-table"
      ref="studentClass"
      :data="studentClassWidget.dataList"
      :size="layoutStore.defaultFormItemSize"
      :seq-config="{startIndex: ((studentClassWidget.currentPage - 1) * studentClassWidget.pageSize)}"
      @sort-change="studentClassWidget.onSortChange"
      header-cell-class-name="table-header-gray"
      @refresh="studentClassWidget.refreshTable()"
    >
      <template #operator>
        <el-button type="primary" :size="layoutStore.defaultFormItemSize"
          @click="onStartTaskClick()">
          新建
        </el-button>
      </template>
      <vxe-column type="seq" title="序号" :width="50" />
      <vxe-column title="工单编号" show-overflow="tooltip" field="workOrderCode" />
      <vxe-column title="班级名称" field="masterData.className" />
      <vxe-column title="所属校区" field="masterData.schoolIdDictMap.name" />
      <vxe-column title="班级级别" field="masterData.classLevelDictMap.name" />
      <vxe-column title="当前任务" field="runtimeTaskInfo.taskName" />
      <vxe-column title="创建时间" field="createTime" />
      <vxe-column title="审批状态" field="latestApprovalStatusDictMap.name" width="100px" />
      <vxe-column title="流程状态" field="flowStatus"  width="100px">
        <template v-slot="scope">
          <span>{{StaticDict.SysFlowWorkOrderStatus.getValue(scope.row.flowStatus)}}</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="150px" fixed="right">
        <template v-slot="scope">
          <el-button type="primary" link :size="layoutStore.defaultFormItemSize"
            v-if="(scope.row.initTaskInfo || {}).taskKey !== (scope.row.runtimeTaskInfo || {}).taskKey"
            @click.stop="onViewTaskClick(scope.row)">
            详情
          </el-button>
          <el-button type="primary" link :size="layoutStore.defaultFormItemSize"
            v-if="(scope.row.initTaskInfo || {}).taskKey === (scope.row.runtimeTaskInfo || {}).taskKey"
            @click.stop="onHandlerTaskClick(scope.row)">
            办理
          </el-button>
          <el-button type="primary" link :size="layoutStore.defaultFormItemSize" class="table-btn"
            @click.stop="onRemindClick(scope.row)">
            催办
          </el-button>
          <el-button type="primary" link :size="layoutStore.defaultFormItemSize" class="table-btn error"
            @click.stop="onCancelTaskClick(scope.row)">
            撤销
          </el-button>
        </template>
      </vxe-column>
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="studentClassWidget.totalCount"
            :current-page="studentClassWidget.currentPage"
            :page-size="studentClassWidget.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="studentClassWidget.onCurrentPageChange"
            @size-change="studentClassWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formFlowClassOrderAI',
};
</script>

<script setup lang="ts">
import { FlowOperationController } from '@/api/flow';
import { SysFlowTaskOperationType } from '@/common/staticDict/flow';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentClassData } from '@/api/generated/studentClassController';
import { CourseData } from '@/api/generated/courseController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { StudentController, StudentClassController, CourseController, SysDeptController } from '@/api/generated';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const processDefinitionKey = 'flowAddClass';
const processDefinitionName = '创建班级审批';

const formFilter = reactive({
  // 班级名称
  classNameFilter: undefined,
  // 班级级别
  classLevelFilter: undefined,
  // 流程状态
  flowStatus: undefined,
  // 工单编号
  workOrderCode: undefined,
  // 创建日期
  createTime: [],
});

const form = ref();

/**
 * 班级级别下拉数据获取函数
 */
const loadClassLevelFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ClassLevel', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 班级级别配置参数
const classLevelFilterOptions: DropdownOptions<DictData> = {
  loadData: loadClassLevelFilterDropdownList,
  isTree: false,
};
// 班级级别下拉组件
const classLevelFilterWidget = useDropdown(classLevelFilterOptions);
const { dropdownList: classLevelFilterWidgetDropdownList } = classLevelFilterWidget

const onReset = () => {
  form.value.resetFields();
  refreshFormFlowClassOrderAI(true);
};

const reset = () => {
  formFilter.flowStatus = undefined;
  formFilter.workOrderCode = undefined;
  formFilter.createTime = [];
  formFilter.classNameFilter = undefined;
  formFilter.classLevelFilter = undefined;
  onReset();
};

const refreshFormFlowClassOrderAI = (reloadData: boolean = false) => {
  if (reloadData) {
    studentClassWidget.value.refreshTable(true, 1);
  } else {
    studentClassWidget.value.refreshTable();
  }
};

// 工单列表
const loadStudentClassData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    flowWorkOrderDtoFilter: {
      flowStatus: formFilter.flowStatus,
      workOrderCode: formFilter.workOrderCode,
      createTimeStart: Array.isArray(formFilter.createTime) ? formFilter.createTime[0] : undefined,
      createTimeEnd: Array.isArray(formFilter.createTime) ? formFilter.createTime[1] : undefined
    },
    studentClassDtoFilter: {
      className: formFilter.classNameFilter,
      classLevel: formFilter.classLevelFilter,
    },
  }
  return new Promise((resolve, reject) => {
    StudentClassController.listWorkOrderFlowAddClass(params).then(res => {
      let dataList = res.data.dataList.map(item => {
        item.initTaskInfo = item.initTaskInfo == null ? {} : JSON.parse(item.initTaskInfo);
        item.runtimeTaskInfo = Array.isArray(item.runtimeTaskInfoList) ? item.runtimeTaskInfoList[0] : undefined;
        item.masterData = item.masterData || {};
        return item;
      });
      resolve({
        dataList: dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    })
  });
};
const loadStudentClassVerify = () => {
  return true;
};
const studentClassOptions: TableOptions<ANY_OBJECT> = {
  loadTableData: loadStudentClassData,
  verifyTableParameter: loadStudentClassVerify,
  paged: true,
  orderFieldName: undefined,
  ascending: true,
};
const studentClassWidget = ref(useTable(studentClassOptions));
// 启动流程
const onStartTaskClick = () => {
  let params: ANY_OBJECT = {
    processDefinitionKey: processDefinitionKey
  }

  FlowOperationController.viewInitialTaskInfo(params).then(res => {
    if (res.data && res.data.taskType === StaticDict.SysFlowTaskType.USER_TASK && res.data.assignedMe) {
      router.push({
        name: res.data.routerName || 'handlerFlowTask',
        query: {
          processDefinitionKey: processDefinitionKey,
          formId: res.data.formId,
          routerName: res.data.routerName,
          readOnly: res.data.readOnly,
          taskName: '启动流程',
          isDraft: true,
          isPreview: false,
          flowEntryName: processDefinitionName,
          variableList: JSON.stringify(res.data.variableList),
          operationList: JSON.stringify(
            (res.data.operationList || []).filter(item => {
              return item.type !== StaticDict.SysFlowTaskOperationType.CO_SIGN && item.type !== StaticDict.SysFlowTaskOperationType.REVOKE;
            }),
          ),
        }
      });
    } else {
      FlowOperationController.startOnly({
        processDefinitionKey: processDefinitionKey
      }).then(res => {
        ElMessage.success('启动成功！');
      }).catch(e => {
        // 异常处理
      });
    }
  }).catch(e => {
    // 异常处理
  });
};
// 办理流程
const onHandlerTaskClick = (row: ANY_OBJECT) => {
  let taskId = (Array.isArray(row.runtimeTaskInfoList) && row.runtimeTaskInfoList.length > 0) ? row.runtimeTaskInfoList[0].taskId : undefined;
  let params: ANY_OBJECT = {
    processInstanceId: row.processInstanceId,
    processDefinitionId: row.processDefinitionId,
    taskId: taskId
  }

  FlowOperationController.viewRuntimeTaskInfo(params).then(res => {
    if (res.data) {
      router.push({
        name: res.data.routerName || 'handlerFlowTask',
        query: {
          isRuntime: true,
          isDraft: row.flowStatus === StaticDict.SysFlowWorkOrderStatus.DRAFT,
          taskId: taskId,
          processDefinitionKey: processDefinitionKey,
          processInstanceId: row.processInstanceId,
          processDefinitionId: row.processDefinitionId,
          formId: res.data.formId,
          routerName: res.data.routerName,
          readOnly: res.data.readOnly,
          taskName: (row.runtimeInitialTask || {}).taskName,
          flowEntryName: row.processDefinitionName,
          processInstanceInitiator: row.processInstanceInitiator,
          operationList: JSON.stringify(
            (res.data.operationList || []).filter(item => {
              return item.type !== StaticDict.SysFlowTaskOperationType.CO_SIGN && item.type !== StaticDict.SysFlowTaskOperationType.REVOKE;
            }),
          ),
          variableList: JSON.stringify(res.data.variableList),
        }
      });
    }
  }).catch(e => {
    // 异常处理
  });
};
// 查看流程
const onViewTaskClick = (row: ANY_OBJECT) => {
  let params: ANY_OBJECT = {
    processInstanceId: row.processInstanceId
  }
  let taskId = (Array.isArray(row.runtimeTaskInfoList) && row.runtimeTaskInfoList.length > 0) ? row.runtimeTaskInfoList[0].taskId : undefined;
  FlowOperationController.viewInitialHistoricTaskInfo(params).then(res => {
    if (res.data) {
      router.push({
        name: res.data.routerName || 'handlerFlowTask',
        query: {
          isRuntime: false,
          taskId: taskId,
          processDefinitionKey: row.processDefinitionKey,
          processInstanceId: row.processInstanceId,
          processDefinitionId: row.processDefinitionId,
          routerName: res.data.routerName,
          readOnly: true,
          flowEntryName: row.processDefinitionName,
          processInstanceInitiator: row.processInstanceInitiator
        }
      });
    }
  }).catch(e => {
    // 异常处理
  });
};
// 催办
const onRemindClick = (row: ANY_OBJECT) => {
  FlowOperationController.remindRuntimeTask({
    workOrderId: row.workOrderId
  }).then(res => {
    ElMessage.success('催办成功');
  }).catch(e => {
    // 异常处理
  });
};
// 撤销流程
const onCancelTaskClick = (row: ANY_OBJECT) => {
  ElMessageBox.confirm('是否撤销此工单？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(res => {
    let params: ANY_OBJECT = {
      workOrderId: row.workOrderId,
      cancelReason: '主动撤销'
    }

    FlowOperationController.cancelWorkOrder(params).then(res => {
      ElMessage.success('撤销成功！');
      refreshFormFlowClassOrderAI();
    }).catch(e => {
      // 异常处理
    });
  }).catch(e => {
    // 取消
  });
};
// 初始化页面数据
const formInit = () => {
  refreshFormFlowClassOrderAI(true);
};

onMounted(() => {
  // 初始化页面数据
  formInit();
});

// TODO 是不是需要申明为外部可调用的方法
defineExpose({ onReset });

onActivated(() => {
  refreshFormFlowClassOrderAI(true);
});
</script>
